<?php
/**
 * Created by PhpStorm.
 * User: chenx
 * Date: 18-3-7
 * Time: 下午10:06
 */

namespace common\service;
use \Qiniu\Auth;
use Qiniu\Storage\UploadManager;


class QiniuService extends BaseService
{

    /**
     * 生成七牛Token
     */
    public static function getToken($bucket=''){
        if(empty($bucket)){
            $bucket = \Yii::$app->params['qiniu']['file_path'];
        }
        $auth = new Auth(\Yii::$app->params['qiniu']['ak'],\Yii::$app->params['qiniu']['sk']);

    // 生成上传Token
        $token = $auth->uploadToken($bucket);
        return $token;
    }


    /**
     * 文件上传
     * @param string $filePath 文件路径
     * @param string $ext 文件后缀
     * @param string $bucket 七牛存储区域
     * @return bool|string
     */
    public static function uploadFile($filePath,$ext='.jpg',$bucket='')
    {
        if(empty($bucket)){
            $bucket = \Yii::$app->params['qiniu']['file_path'];
        }
        // 生成上传 Token
        $token = self::getToken($bucket);
        // 要上传文件的本地路径
        // 上传到七牛后保存的文件名
        $key = md5(file_get_contents($filePath).time()).$ext;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        }
        if(isset($ret['key'])){
            return $ret['key'];
        }
        return false;

    }

    /**
     * 用来传数据流 string对象 有问题
     * @param string $stream
     * @param string $ext
     * @param string $bucket
     * @return bool|string
     */
    public static function uploadFileByStream($stream,$ext='.jpg',$bucket='')
    {

        if(empty($bucket)){
            $bucket = \Yii::$app->params['qiniu']['file_path'];
        }
        $token = self::getToken($bucket);
        $uploadMgr = new UploadManager();
        $key = md5($stream.time()).$ext;
        list($ret, $err) = $uploadMgr->put($token, $key, $stream);

        if ($err !== null) {
            return false;
        }

        if(isset($ret['key'])){
            return $ret['key'];
        }
        return false;

    }

}